<template>
  <div class="work-container">
    <div class="container-box scroll-box">
      <div class="order-type-box">
        <div>
          <span class="app-form-red">*</span>
          <span class="add-name-text">工单类型</span>
        </div>
        <div>
          <van-cell
            is-link
            :title="sheetWorkValue"
            @click="sheetShow = true"
          />
        </div>
      </div>
      <div>
        <div class="add-name-box">
          <span class="app-form-red">*</span>
          <span class="add-name-text">选择设备</span>
        </div>
        <van-field
          readonly
          v-model="deviceName"
          placeholder="请选择"
          :error-message="deviceNameError"
          right-icon="arrow"
          @click="onOpenVar"
        />
      </div>
      <div>
        <div class="add-name-box">
          <span class="add-name-text">{{explainTrue?'保养说明':'故障描述'}}</span>
        </div>
        <van-field
          v-model="deviceExplain"
          type="textarea"
          rows="3"
          autosize
          placeholder="限输入100字"
          maxlength="100"
          show-word-limit
        />
      </div>
      <div
        class="workReport-padding"
        v-show="!explainTrue"
        v-has="'maintenanceCenter:repair-report'"
      >
        <div class="workReport-box ">
          <div class="workReport-top">
            <span class="workReport-name-text">上报供应商</span>
            <van-switch
              v-model="workReport"
              size="24px"
            />
          </div>
          <p class="workReport-tips-text">上报维修工单给供应商，由供应商安排维修人员进行处理。</p>
        </div>
      </div>
      <div>
        <div class="add-name-box">
          <span class="app-form-red">*</span>
          <span class="add-name-text">现场联系人</span>
        </div>
        <van-field
          v-model="workContacts"
          placeholder="限输入6字"
          maxlength="6"
          :error-message="workContactsError"
          @input="workContacts = workContacts.replace(/^ +| +$/g,'')"
        />
      </div>
      <div>
        <div class="add-name-box">
          <span class="app-form-red">*</span>
          <span class="add-name-text">联系人电话</span>
        </div>
        <van-field
          v-model="workPhone"
          placeholder="请输入"
          maxlength="11"
          :error-message="workPhoneError"
          @input="workPhone = workPhone.replace(/[^\d]/g, '')"
        />
      </div>

      <div class="workReport-padding">
        <div class="workReport-box">
          <div>
            <span class="add-name-text">现场图片</span>
            <div class="img-tips-text">图片不大于2M，最多不能超过5张</div>
          </div>
          <div class="img-box">
            <van-uploader
              v-model="imgList"
              max-count="5"
              :before-read="uploadImg"
            />
          </div>

        </div>
      </div>

      <div>
        <div class="add-name-box">
          <span class="add-name-text">设备地址</span>
        </div>
        <van-field
          v-model="deviceAddres"
          placeholder="限输入30字"
          maxlength="30"
          @input="deviceAddres = deviceAddres.replace(/^ +| +$/g,'')"
        />
      </div>
      <div>
        <div class="add-name-box">
          <span class="add-name-text">所属公司</span>
        </div>
        <van-field
          v-model="workCompany"
          placeholder="自动获取"
          disabled
          error-message=""
        />
      </div>
    </div>
    <div class="button-margin">
      <van-button
        block
        type="info"
        @click="submitAdd()"
      >确 定</van-button>
    </div>

    <van-action-sheet
      v-model="sheetShow"
      :actions="sheetActions"
      cancel-text="取消"
      close-on-click-action
      @select="onSheetSelect"
    />

    <van-popup
      v-model="showVarBox"
      position="bottom"
      :close-on-click-overlay="false"
      :style="{ height: '64%' }"
    >
      <div class="var-box">
        <div class="var-box-header">
          <span class="model-name">{{ deviceModelName || '' }}</span>
          <!-- <p class="model-choose">已选择（<span class="color-primary">{{ chooseVarData.length }}</span>/5）</p> -->
        </div>
        <div class="var-search-box">
          <form action="/">
            <van-search
              v-model="searchKey"
              shape="round"
              placeholder="搜索设备编号/设备名称"
              clearable
              @search="handleSearch"
              @clear="handleClear"
            />
          </form>
        </div>
        <ul class="var-list scroll-box">
          <li
            v-for="(item, index) in filterVarList"
            :key="item.number"
            :class="{'color-primary': item.checked}"
            @click="selectVar(item, index)"
          >
            <span>{{ item.label}}</span>
            <van-icon
              name="success"
              v-if="item.checked"
            />
          </li>
        </ul>
        <ul class="operate-box">
          <li @click="cancelSelect">取消</li>
          <li
            class="color-primary"
            @click="confirmSelect"
          >确定</li>
        </ul>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { Form, ActionSheet, Cell, CellGroup, Field, Button, Switch, Uploader, Popup, Search, Toast } from 'vant';
import {
  createOrder,
  uploadFile,
  getDeviceList,
  getDeviceLastProject,
  getDeviceLastContact,
  getOrderList
} from '@/api/maintenanceView';
export default {
  components: {
    [Form.name]: Form, //表单
    [ActionSheet.name]: ActionSheet, //动作面板
    [Field.name]: Field, //输入框
    [Button.name]: Button, //按钮
    [Switch.name]: Switch, //开关
    [Cell.name]: Cell, //单元格
    [CellGroup.name]: CellGroup, //单元格
    [Uploader.name]: Uploader, //上传文件
    [Popup.name]: Popup, //弹窗
    [Search.name]: Search, //搜索
    [Toast.name]: Toast //提示
  },
  data() {
    return {
      sheetShow: false, //打开面板
      sheetActions: [{ name: '维修工单' }, { name: '保养工单' }],
      sheetWorkValue: '维修工单',
      deviceName: '', //设备名称
      deviceNameError: '',
      deviceId: '', //设备id
      deviceExplain: '', //故障描述
      explainTrue: false, //判断是故障描述还是保养说明
      workReport: false, //上次供应商
      workContacts: '', //现场联系人
      workPhone: '', //联系人电话
      deviceAddres: '', //设备地址
      workCompany: '', //所属公司
      project_contract: '', //合同编号
      imgList: [],
      workContactsError: '', //现场联系人提示
      workPhoneError: '', //联系人电话提示
      showVarBox: false, //打开选择弹窗
      searchKey: '', //选择框搜索
      varTotal: 0, //总数
      varList: [], //全部数据
      filterVarList: [],
      deviceModelName: '选择设备', //选择框搜索标题
      chooseVarData: [],
      openBefore: []
    };
  },
  beforeRouteEnter(to, from, next) {
    // console.log(to, '组件独享守卫beforeRouteEnter第一个参数');
    // console.log(from, '组件独享守卫beforeRouteEnter第二个参数');
    // console.log(next, '组件独享守卫beforeRouteEnter第三个参数');
    next(vm => {
      if (to.query.code) {
        to.meta.title = '重新创建工单';
      } else {
        to.meta.title = '创建工单';
      }
    });
  },
  mounted() {
    this.onDeviceList();
    this.onListData();
  },
  methods: {
    //列表数据-做回显
    onListData() {
      if (this.$route.query.code) {
        let params = {
          page: 1, //当前页
          page_size: 1, //每页显示数据条数
          order_no: this.$route.query.code
        };
        getOrderList(params).then(res => {
          // this.listData = res.data.list;
          //回显
          this.sheetWorkValue = res.data.list[0].order_type === 1 ? '维修工单' : '保养工单';
          this.explainTrue = res.data.list[0].order_type === 1 ? false : true;
          this.deviceName = res.data.list[0].device_number + '/' + res.data.list[0].device_name;
          this.deviceId = res.data.list[0].device_id;
          this.chooseVarData = [{ id: res.data.list[0].device_id }];
          this.deviceExplain = res.data.list[0].description;
          this.workContacts = res.data.list[0].contacts;
          this.workPhone = res.data.list[0].contacts_tel;
          this.deviceAddres = res.data.list[0].address;
          this.workCompany = res.data.list[0].customer_name;
          this.project_contract = res.data.list[0].project_contract;
          if (res.data.list[0].source === 3) {
            this.workReport = true;
          } else {
            this.workReport = false;
          }
          let imgArr = JSON.parse(res.data.list[0].photos);
          imgArr.map(item => {
            this.imgList.push({ url: item });
          });
        });
      }
    },
    //选择工单类型
    onSheetSelect(item) {
      this.show = false;
      if (item.name === '保养工单') {
        this.explainTrue = true;
      } else {
        this.explainTrue = false;
      }
      this.explainTrue;
      this.sheetWorkValue = item.name;
    },
    uploadImg(file) {
      //上传图片
      const isLt3M = file.size / 1024 / 1024 < 2;
      if (!isLt3M) {
        Toast('只能上传小于2M!');
        this.files = null;
        return;
      }
      this.files = file;
      // FormData 对象
      let formData = new FormData();
      // 文件对象
      formData.append('file', this.files);
      uploadFile(formData).then(res => {
        this.imgList.push({ url: res.data.path });
      });
    },
    //新增工单
    submitAdd() {
      this.deviceNameError = '';
      this.workContactsError = '';
      this.workPhoneError = '';
      if (this.deviceId === '') {
        this.deviceNameError = '请选择设备';
        return;
      }
      if (this.workContacts === '') {
        this.workContactsError = '现场联系人必填';
        return;
      }
      if (this.workPhone === '') {
        this.workPhoneError = '联系人电话必填';
        return;
      }
      let params = {};
      params.address = this.deviceAddres;
      params.contacts = this.workContacts;
      params.contacts_tel = this.workPhone;
      params.description = this.deviceExplain;
      params.device_id = this.deviceId;
      params.is_report = this.workReport ? 2 : 1;
      params.order_type = this.sheetWorkValue === '维修工单' ? 1 : 2;
      params.project_contract = this.project_contract;

      if (params.is_report === 2) {
        params.source = 3;
      } else {
        params.source = 1;
      }

      params.photos = [];
      this.imgList.forEach(res => {
        params.photos.push(res.url);
      });
      createOrder(params).then(res => {
        if (this.$route.query.code) {
          this.$toast({
            message: '重新创建工单成功',
            onClose: () => {
              this.$router.go(-2);
            }
          });
        } else {
          this.$toast({
            message: '创建工单成功',
            onClose: () => {
              this.$router.back();
            }
          });
        }
      });
    },
    //选择设备
    //设备数据
    onDeviceList() {
      getDeviceList().then(res => {
        this.varList = res.data.list;
        this.varList.map(item => {
          item.label = item.number + '/' + item.name;
          item.value = item.id;
          item.checked = false;
        });
        // //回显勾选
        // if (this.chooseVarData.length) {
        //   this.chooseVarData.map(item => {
        //     this.varList.map(subItem => {
        //       if (subItem.id === item.id) {
        //         subItem.checked = true;
        //       }
        //     });
        //   });
        // }
        this.filterVarList = this.varList;
      });
    },
    //打开
    onOpenVar() {
      this.showVarBox = true;
      this.varList.map(item => {
        item.label = item.number + '/' + item.name;
        item.value = item.id;
        item.checked = false;
      });
      //回显勾选
      if (this.chooseVarData.length) {
        this.chooseVarData.map(item => {
          this.varList.map(subItem => {
            if (subItem.id === item.id) {
              subItem.checked = true;
            }
          });
        });
      }
      this.filterVarList = this.varList;
      this.openBefore = JSON.parse(JSON.stringify(this.chooseVarData));
    },
    // 搜索变量
    handleSearch() {
      let filterArr = this.varList.filter(item => {
        return item.label.indexOf(this.searchKey) !== -1;
      });
      this.filterVarList = filterArr;
    },
    // 清空搜索
    handleClear() {
      this.filterVarList = this.varList;
    },
    // 选择变量
    selectVar(item, index) {
      this.chooseVarData = [];
      if (!item.checked) {
        this.filterVarList.map((fitem, findex) => {
          if (index === findex) {
            fitem.checked = true;
          } else {
            fitem.checked = false;
          }
        });
        this.$forceUpdate();
        this.chooseVarData.push(item);
      } else {
        item.checked = false;
        this.$forceUpdate();
      }
    },
    // 取消变量选择
    cancelSelect() {
      this.showVarBox = false;
      this.chooseVarData = this.openBefore;
    },
    // 确定变量选择
    confirmSelect() {
      if (this.chooseVarData.length === 0) {
        this.deviceAddres = '';
        this.workCompany = '';
        this.deviceId = '';
        this.deviceName = '';
        this.project_contract = '';
        this.workContacts = '';
        this.workPhone = '';
        this.showVarBox = false;
        this.$forceUpdate();
        return;
      } else {
        this.deviceAddres =
          this.chooseVarData[0].countries +
          this.chooseVarData[0].province +
          this.chooseVarData[0].city +
          this.chooseVarData[0].address;
        this.workCompany = this.chooseVarData[0].company;
        this.deviceId = this.chooseVarData[0].id;
        this.deviceName = this.chooseVarData[0].label;
        //选中设备获取到合同编号
        getDeviceLastProject({ device_id: this.chooseVarData[0].id }).then(res => {
          this.project_contract = res.data.contacts;
        });

        //选中设备最新工单联系人
        getDeviceLastContact({ device_id: this.chooseVarData[0].id }).then(res => {
          this.workContacts = res.data.contacts;
          this.workPhone = res.data.contacts_tel;
        });

        this.showVarBox = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.work-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background-color: #fff;
}
.container-box {
  flex: 1;
}

.app-form-red {
  color: #f56c6c;
  font-size: 0.32rem;
}
.add-name-box {
  margin-left: 0.426667rem;
}
.add-name-text {
  color: #666666;
  font-size: 0.32rem;
}

::v-deep .van-field__value {
  border-bottom: 1px solid #f2f6fc;
  padding: 0.133333rem 0;
}
//选择设备搜索框
::v-deep .var-search-box .van-field__value {
  padding: 0;
}

.order-type-box {
  border-bottom: 1px solid #f2f6fc;
  margin: 0.213333rem 0.426667rem;
  ::v-deep .van-cell--clickable {
    padding-left: 0;
    padding-right: 0;
  }
}

//上报供应商
.workReport-padding {
  padding: 0 0.426667rem;
  margin-bottom: 0.213333rem;
  .workReport-box {
    border-bottom: 1px solid #f2f6fc;
  }
  .workReport-top {
    display: flex;
    justify-content: space-between;
  }
  .workReport-name-text {
    margin-top: 0.266667rem;
    color: #666666;
    font-size: 0.373333rem;
  }
  .workReport-tips-text {
    font-size: 0.346667rem;
    color: #999999;
    padding: 0.4rem 0;
  }
}
.img-box {
  margin-top: 0.426667rem;
}
.img-tips-text {
  font-size: 0.32rem;
  color: #999999;
  padding-top: 0.133333rem;
}

//按钮
.button-margin {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 1.493333rem;
  padding: 0.213333rem 0.426667rem;
  background-color: #fff;
}
::v-deep .van-button {
  border-radius: 0.106667rem;
}

//选择器
.van-popup--bottom {
  border-top-left-radius: 0.426667rem;
  border-top-right-radius: 0.426667rem;

  .var-box {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .var-box-header {
      flex-shrink: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.213333rem;
      padding: 0 0.426667rem;
      padding-top: 0.426667rem;

      .model-name {
        margin-right: 0.266667rem;
        font-size: 0.426667rem;
        line-height: 0.533333rem;
      }

      .model-choose {
        flex-shrink: 0;
        color: var(--color-deep-gary);
        font-size: 0.32rem;
      }
    }

    .var-search-box {
      flex-shrink: 0;
      margin-bottom: 0.213333rem;
      border-bottom: 1px solid var(--border-color);
    }

    .var-list {
      flex: 1;
      width: 100%;
      padding: 0 0.426667rem;

      li {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.32rem 0;
        font-size: 0.373333rem;
        border-bottom: 1px solid var(--border-color);

        &:last-of-type {
          border-bottom: 0;
        }
      }
    }

    .operate-box {
      flex-shrink: 0;
      display: flex;
      width: 100%;
      height: 1.28rem;
      border-top: 1px solid var(--border-color);

      li {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 50%;
        font-size: 0.426667rem;

        &:first-of-type {
          &::after {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 1px;
            height: 100%;
            background-color: var(--border-color);
          }
        }
      }
    }
  }
}
</style>